//
//  MainViewController.m
//  WZCLApp
//
//  Created by chirui on 2018/7/2.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "MainViewController.h"
#import "LogingViewController.h"
#import "MainTableViewCell.h"
#import "TextView.h"
#import "RecomListViewController.h"
#import "EducationListViewController.h"
#import "ShopMainViewController.h"
#import "MainListDetailsViewController.h"

@interface MainViewController ()<HTHorizontalSelectionListDataSource,HTHorizontalSelectionListDelegate,UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,UITextFieldDelegate>{
    NSDictionary * dataDic;
    UITableView * _tableView;
     TextView * pmView;
    NSMutableArray * _titileArray;
    NSArray * titleClassArray;
    
    NSMutableArray * _dataArray;
    int _page;
    int _totailPage;

}
@property(nonatomic,strong)HTHorizontalSelectionList * selectionList;
@property (nonatomic,strong) ImageTextButton * areButton;

@end

@implementation MainViewController

-(void)viewWillAppear:(BOOL)animated{
    
    [_tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _page = 1;
    self.areButton = [[ImageTextButton alloc] initWithFrame:CGRectMake(10, 16, 60,40 )
                                                      image:[UIImage imageNamed:@"icon_drop_down"]
                                                      title:@"成都 "];
    self.areButton.buttonTitleWithImageAlignment = UIButtonTitleWithImageAlignmentRight;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.areButton];
    
    self.navigationItem.titleView = [SearchView  creatSearchTextFieldForDelegate:self Placeholder:@"请输入搜索内容"];
  
    _titileArray = @[].mutableCopy;
    _dataArray = @[].mutableCopy;
    [self creatTableView];
    [self getMainDataRequest];
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    [textField resignFirstResponder];
    
//    SearchViewController * search = [[SearchViewController alloc]init];
//    search.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:search animated:YES];
    NSLog(@"跳转搜索页");
}

-(void)btnClick{
    
    LogingViewController * login = [[LogingViewController alloc]init];
    
    [self presentViewController:login animated:YES completion:^{
        
    }];
}

-(void)creatTableView {
    
    _tableView  =[[UITableView alloc]initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT-SH_TabBarHeight-SH_NavBarHeight-SH_StatusBarHeight)
                                             style:UITableViewStyleGrouped];
    _tableView.dataSource=self;
    _tableView.delegate =self;
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView =view;
    
    [_tableView registerNib:[UINib nibWithNibName:@"MainTableViewCell" bundle:nil] forCellReuseIdentifier:[MainTableViewCell reuseIdentifier]];
    
    [self.view addSubview:_tableView];
//
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
     
        [_tableView reloadData];
        _page = 1;
        [self getMainDataRequest];
        [self getListDataRequest];

    }];
    _tableView.mj_header = header;
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page ++;
         [self getListDataRequest];

    }];
    footer.automaticallyRefresh = YES;
    _tableView.mj_footer =footer;

    if (_dataArray.count>10) {
        _tableView.mj_footer.hidden = NO;
    }else{
        _tableView.mj_footer.hidden = YES;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPat{
    
    return 100;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return  810;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    NSDictionary * dic = _dataArray[indexPath.row];
    MainTableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:[MainTableViewCell reuseIdentifier]];
    

    [cell.heardImage sd_setImageWithURL:[NSURL URLWithString:dic[@"cover"]] placeholderImage:[UIImage imageNamed:@"img_1"]];
    cell.titleLabel.frame = CGRectMake(109, 10, WIDTH - 120, 20);
    NSString * titleStr = dic[@"title"];
    cell.titleLabel.text = titleStr;

    cell.titleLabel.numberOfLines = 2;
    [cell.titleLabel sizeToFit];

    cell.detailsLabel.frame = CGRectMake(109, CGRectGetMaxY(cell.titleLabel.frame)+4, WIDTH - 140, 20);
    cell.numberLabel.text = dic[@"read"];
    cell.detailsLabel.text = dic[@"source"];
    cell.timeLabel.text = dic[@"create_time"];
    return cell;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary * dic = _dataArray[indexPath.row];
    MainListDetailsViewController * details = [[MainListDetailsViewController alloc]init];
    details.dataDic= dic;
    details.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:details animated:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    
    NSMutableArray * imageArrray = @[].mutableCopy;

    [imageArrray removeAllObjects];

    if ([dataDic[@"banner"] isKindOfClass:[NSArray class]]) {

        for (NSDictionary * dic in dataDic[@"banner"]) {

            [imageArrray addObject:dic[@"image"]];
        }
    }
    
    UIView * topView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 700)];
    topView.backgroundColor =[UIColor groupTableViewBackgroundColor];
    
    for (UIView * view in topView.subviews) {
        
        [view removeFromSuperview];
    }
    
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH, 180) delegate:self placeholderImage:[UIImage imageNamed:@"img_2"]];
    cycleScrollView.backgroundColor = [UIColor whiteColor];
    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    cycleScrollView.currentPageDotColor = MyTabbarClick;
    cycleScrollView.autoScrollTimeInterval = 4;
    cycleScrollView.imageURLStringsGroup = imageArrray;
    [topView addSubview:cycleScrollView];
    cycleScrollView.clickItemOperationBlock = ^(NSInteger index) {
        
    };
    
    UIView * classView = [[UIView alloc]initWithFrame:CGRectMake(0, 180, WIDTH, 200)];
    classView.backgroundColor = [UIColor whiteColor];
    
    CGFloat imageWide = 60;
    CGFloat gapWide = (WIDTH - 60*5)/5;
    
    NSMutableArray * imagebtnArray = @[].mutableCopy;
    
    
    if (imagebtnArray) {
        
        [imagebtnArray removeAllObjects];
        
    }
    
    if (dataDic) {
        
        
        if ([dataDic[@"category"] isKindOfClass:[NSArray class]]) {
            
            for (NSDictionary * dic in dataDic[@"category"]) {
                
                [imagebtnArray addObject:dic];
                
            }
        }
    
    UILabel *label;
    for (int i = 0; i < imagebtnArray.count; i++) {
        
        NSDictionary * dic = imagebtnArray[i];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        btn.frame = CGRectMake( gapWide/2+gapWide *(i%5)+imageWide*(i%5), 10+15 *(i/5)+(imageWide+15)*(i/5) , imageWide, imageWide);
        btn.tag = 100 + i;
        btn.layer.cornerRadius = 30.f;
        btn.layer.masksToBounds = YES;
        [btn sd_setBackgroundImageWithURL:ImageUrl(dic[@"cover_photo"]) forState:UIControlStateNormal];
        btn.backgroundColor =[UIColor whiteColor];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [classView addSubview:btn];
        
        label = [[UILabel alloc]init];
        label.center = CGPointMake(btn.center.x, btn.center.y + imageWide / 2.f +10);
        label.bounds = CGRectMake(0, 0, 100, 15);
        label.font = [UIFont systemFontOfSize:13];
        label.textColor = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = dic[@"cate_name"];
        [classView addSubview:label];
    }
    }
    [topView addSubview:classView];
    
    UIView * educationView = [[UIView alloc]initWithFrame:CGRectMake(0, 381, WIDTH, 80)];
    educationView.backgroundColor = [UIColor whiteColor];
 
    UIButton * eduBtn  =[[UIButton alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 80)];
    [eduBtn addTarget:self action:@selector(eduBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIImageView * educatImage = [[UIImageView alloc]initWithFrame:CGRectMake(10, 15, 50, 50)];
    educatImage.image = [UIImage imageNamed:@"icon_home_headline"];
    [educationView addSubview:educatImage];
    
    NSMutableArray * array = @[].mutableCopy;
    
    if (array) {
        
        [array removeAllObjects];
    }
    if (dataDic) {
        for (NSDictionary * dic in dataDic[@"edu"]) {
            
            [array addObject:dic[@"title"]];
        }
    }else {
        
        [array addObject:@""];
    }
  
  
    
    pmView = [[TextView alloc]initWithFrame:CGRectMake(80, 10, WIDTH- 100, 60)];
    pmView.backgroundColor = [UIColor whiteColor];
    //    pmView.layer.cornerRadius = 3;
    pmView.showNumber = true;//true 显示1排，，false显示2排
    pmView.clipsToBounds = YES;
    [pmView animationWithTexts:array];
    [educationView addSubview:pmView];
    [educationView addSubview:eduBtn];
//    if (_dataArray.count==0) {
//        [pmView animationWithTexts:[NSMutableArray arrayWithObjects:@"", nil]];
//    }else{
    
//    }
    
    [self creatLabelFrame:CGRectMake(15, 475, 100, 20) andTitle:@"更多服务" andtitleColor:[UIColor blackColor] andFonut:17 onView:topView];
    
    UIView * severView = [[UIView alloc]initWithFrame:CGRectMake(0, 500, WIDTH, 210)];
    severView.backgroundColor = [UIColor clearColor];
    
    float width  = (WIDTH - 30)/2;
    if (dataDic) {
        
        if ([dataDic[@"ads"] isKindOfClass:[NSArray class]]) {
            
            NSArray * array = dataDic[@"ads"];
       
        for (int i = 0; i<array.count; i++) {
            NSDictionary * dic = array[i];
            UIButton * severBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            severBtn.frame = CGRectMake(10 + 10*(i%2)+width * (i%2), 10 + 10*(i/2)+55 *(i/2), width, 55);
            [severBtn sd_setBackgroundImageWithURL:ImageUrl(dic[@"cover_photo"]) forState:UIControlStateNormal];
            severBtn.tag = i+100;
            severBtn .backgroundColor = [UIColor orangeColor];
            [severBtn addTarget:self action:@selector(severBtn:) forControlEvents:UIControlEventTouchUpInside];
            [severView addSubview:severBtn];
        }
      }
       
    }
    
   
     [topView addSubview:severView];
    UIView * scrollTitleView = [[UIView alloc]initWithFrame:CGRectMake(0, 710, WIDTH, 100)];
    scrollTitleView.backgroundColor = [UIColor whiteColor];
    
    
     [self creatLabelFrame:CGRectMake(15, 15, 100, 20) andTitle:@"今日推荐" andtitleColor:[UIColor blackColor] andFonut:17 onView:scrollTitleView];
    
    ImageTextButton *  moreButton = [[ImageTextButton alloc] initWithFrame:CGRectMake(WIDTH - 60,10 , 60,30 )
                                                      image:[UIImage imageNamed:@"icon_information_more"]
                                                      title:@"更多"];
    moreButton.buttonTitleWithImageAlignment = UIButtonTitleWithImageAlignmentRight;
    [moreButton addTarget:self action:@selector(moreBtn) forControlEvents:UIControlEventTouchUpInside];
    [scrollTitleView addSubview:moreButton];
    
    self.edgesForExtendedLayout =UIRectEdgeNone;
    
    _selectionList =[[HTHorizontalSelectionList alloc]initWithFrame:CGRectMake(0, 50, WIDTH, 50)];
    _selectionList.dataSource=self;
    _selectionList.delegate=self;
    [scrollTitleView addSubview:_selectionList];
    [_selectionList setTitleFont:[UIFont systemFontOfSize:15] forState:UIControlStateSelected];
    [_selectionList setTitleFont:[UIFont systemFontOfSize:15] forState:UIControlStateNormal];
    [_selectionList setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_selectionList setTitleColor:MyTabbarClick forState:UIControlStateSelected];
    //设置button之间的间距
    float WidthBtnFloat;
    if (ISP4||ISP5) {
        WidthBtnFloat =5;
    }else if (ISP6){
        WidthBtnFloat =10;
    }else {
        WidthBtnFloat =15;
    }
//    UIView * line =[[UIView alloc]initWithFrame:CGRectMake(0, 49, WIDTH, 1)];
//    line.backgroundColor =Color(248, 248, 248);
//    [_selectionList addSubview:line];
    _selectionList.buttonInsets= UIEdgeInsetsMake(5,WidthBtnFloat, 5, WidthBtnFloat);
    //滑动按钮下边的滑块设置
    _selectionList.selectionIndicatorColor = MyTabbarClick;
    _selectionList.selectionIndicatorHeight =3;
    _selectionList.bottomTrimColor =[UIColor whiteColor];
    
    [topView addSubview:scrollTitleView];
    [topView addSubview:educationView];
    
    return topView;
}

-(void)eduBtnClick{
    
    EducationListViewController * educat = [[EducationListViewController alloc]init];
    educat.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:educat animated:YES];
    
}

//更多服务
-(void)severBtn:(UIButton *)btn{
     NSArray * array = dataDic[@"ads"];
    NSDictionary * dic = array[btn.tag -100];
    NSLog(@"dic = %@",dic);
    
}

//分类
-(void)btnClick:(UIButton *)btn{
    
    ShopMainViewController * shopMain = [[ShopMainViewController alloc]init];
    shopMain.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:shopMain animated:YES];
}

// 更多推荐
-(void)moreBtn{
    
    RecomListViewController * recom = [[RecomListViewController alloc]init];
    recom.hidesBottomBarWhenPushed = YES;
    recom.index = 0;
    recom.classArray = dataDic[@"info_cate"];
    [self.navigationController pushViewController:recom animated:YES];
}

#pragma mark------HTHorizontalSelectionListDelegate实现--
//点击效果
-(void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index{
    
    RecomListViewController * recom = [[RecomListViewController alloc]init];
    recom.hidesBottomBarWhenPushed = YES;
    recom.index = index;
    recom.classArray = dataDic[@"info_cate"];
    [self.navigationController pushViewController:recom animated:YES];
    
}
//返回下表对应的文字按钮
-(NSString *)selectionList:(HTHorizontalSelectionList *)selectionList titleForItemWithIndex:(NSInteger)index{
    
    return _titileArray[index];
}
//多少个
-(NSInteger)numberOfItemsInSelectionList:(HTHorizontalSelectionList *)selectionList{
    
    return _titileArray.count;
    
}

-(void)creatLabelFrame:(CGRect)rec andTitle:(NSString *)titleStr andtitleColor:(UIColor *)col andFonut:(CGFloat)flo onView:(UIView *)view{
    
    UILabel * label = [[UILabel alloc]initWithFrame:rec];
    label.text = titleStr;
    label.textColor = col;
    label.font = [UIFont systemFontOfSize:flo];
    [view addSubview:label];
}

-(void)getMainDataRequest{
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_mainData_api) andparameters:nil Success:^(id responseObject) {
        
        if (codeSucess) {
            
            dataDic = responseObject[@"datas"];
        }
        
        if (_titileArray) {
            [_titileArray removeAllObjects];
        }
        if ([dataDic[@"info_cate"] isKindOfClass:[NSArray class]]) {
            
            titleClassArray = dataDic[@"info_cate"];
        }
        for (NSDictionary * dic in titleClassArray) {
            
            [_titileArray addObject:dic[@"name"]];
        }
        [self getListDataRequest];
        [_tableView.mj_header endRefreshing];
        [_tableView reloadData];
    } failed:^(NSError *error) {
        SHuiMBhudTextNetError;
    }];

}

-(void)getListDataRequest{
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_tableView.mj_footer setState: MJRefreshStateNoMoreData];
            
            return ;
        }
    }
    NSDictionary * dic = @{@"page":[NSString stringWithFormat:@"%d",_page],
                           @"tag":@"news",
                           @"per_page":@"10",
                           @"type_id": titleClassArray[0][@"id"],
                           @"if_hot":@"yes"
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_mainNews_api) andparameters:dic Success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue]==200) {
            
            _totailPage = [responseObject[@"datas"][@"total_page"]  intValue];
            
            if (_page==1) {
                
                if (_dataArray) {
                    
                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
                
            }else {
                
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }
            if (_dataArray.count>0) {
              
                if (_dataArray.count<10) {
                    
                    _tableView.mj_footer.hidden = YES;
                }
            }else {
                _tableView.mj_footer.hidden = YES;
              
            }
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
            
        }
        
        [_tableView.mj_footer endRefreshing];
        [_tableView.mj_header  endRefreshing];
        [_tableView reloadData];
        
        
    } failed:^(NSError *error) {
        [_tableView.mj_header endRefreshing];
        [_tableView reloadData];
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
    
    
}


@end
